package com.yalantis.ucrop.util;

import ohos.agp.utils.RectFloat;

public class RectUtils {

    /**
     * Gets a float array of the 2D coordinates representing a rectangles
     * corners.
     * The order of the corners in the float array is:
     * 0------->1
     * ^        |
     * |        |
     * |        v
     * 3<-------2
     *
     * @param r the rectangle to get the corners of
     * @return the float array of corners (8 floats)
     */
    public static float[] getCornersFromRect(RectFloat r) {
        return new float[]{
                r.left, r.top,
                r.right, r.top,
                r.right, r.bottom,
                r.left, r.bottom
        };
    }

    /**
     * Gets a float array of two lengths representing a rectangles width and height
     * The order of the corners in the input float array is:
     * 0------->1
     * ^        |
     * |        |
     * |        v
     * 3<-------2
     *
     * @param corners the float array of corners (8 floats)
     * @return the float array of width and height (2 floats)
     */
    public static float[] getRectSidesFromCorners(float[] corners) {
        return new float[]{(float) Math.sqrt(Math.pow(NumCalcUtil.subtract(corners[0] , corners[2]), 2)
                + Math.pow(NumCalcUtil.subtract(corners[1] , corners[3]), 2)),
                (float) Math.sqrt(Math.pow(NumCalcUtil.subtract(corners[2] , corners[4]), 2)
                        + Math.pow(NumCalcUtil.subtract(corners[3] , corners[5]), 2))};
    }

    public static float[] getCenterFromRect(RectFloat r) {
        return new float[]{(NumCalcUtil.add(r.left , r.right)) /2, (NumCalcUtil.add(r.top , r.bottom)) /2};
    }

    /**
     * Takes an array of 2D coordinates representing corners and returns the
     * smallest rectangle containing those coordinates.
     *
     * @param array array of 2D coordinates
     * @return smallest rectangle containing coordinates
     */
    public static RectFloat trapToRect(float[] array) {
        RectFloat r = new RectFloat(Float.POSITIVE_INFINITY, Float.POSITIVE_INFINITY,
                Float.NEGATIVE_INFINITY, Float.NEGATIVE_INFINITY);
        for (int i = 1; i < array.length; i += 2) {
            float x = Math.round(array[i - 1] * 10) / 10.f;
            float y = Math.round(array[i] * 10) / 10.f;
            r.left = Math.min(x, r.left);
            r.top = Math.min(y, r.top);
            r.right = Math.max(x, r.right);
            r.bottom = Math.max(y, r.bottom);
        }
        reorder(r);
        return r;

    }

    private static void reorder(RectFloat r){
        if(r.right <= r.left){
            float temp = r.right;
            r.right = r.left;
            r.left = temp;
        }
        if(r.bottom <= r.top){
            float temp = r.bottom;
            r.bottom = r.top;
            r.top = temp;
        }
    }

}